package com.example.demo.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.Util.Http;
import com.example.demo.Util.UUIDHexGenerator;
import com.example.demo.config.ApiConstant;
import com.example.demo.config.jwt.JwtConfig;
import com.example.demo.dto.JwtTokenVo;
import com.example.demo.entity.User;
import com.example.demo.entity.Userinfo;
import com.example.demo.services.IUserService;
import com.example.demo.services.IUserinfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Fyly
 * @since 2019-02-20
 */

@Api(value = "用户controller", tags = {"用户操作接口"})
@RestController
@RequestMapping("/api/User/")
public class UserController {

    @Autowired
    private IUserService iuserService;

    @Autowired
    private IUserinfoService iuserinfoService;

    @Resource
    private JwtConfig jwtConfig;


    @ApiOperation(value = "根据用户id 查询用户")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long", paramType = "query"),
//            @ApiImplicitParam(name = "date", value = "book's date", required = false, dataType = "string", paramType = "query")})
//   @RequestMapping(value ="getUser")
    @GetMapping(value = "getUser")
    @ResponseBody
    public User getUser(@RequestParam(value = "id") int id, @RequestParam(value = "username") String username) {
        User user = iuserService.getUserById(id);
        System.out.println(user);
        return user;
    }


    /**
     * 用户登录
     *
     * @param code
     * @return
     */

    @ApiOperation(value = "登录接口")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long", paramType = "query"),
//            @ApiImplicitParam(name = "date", value = "book's date", required = false, dataType = "string", paramType = "query")})
//   @RequestMapping(value ="getUser")
    @GetMapping(value = "doLogin")
    @ResponseBody
    public Map<String, Object> doLogin(String code, String avatarUrl, int gender, String nickName, HttpSession session) {


          //根据code获取openid
          JSONObject SessionKeyOpenId = getOpenId(code);
          String openid = SessionKeyOpenId.getString("openid");
          String sessionKey = SessionKeyOpenId.getString("session_key");


        //查找用户记录
        User user = iuserService.selectByOpenid(openid);


        if (user == null) {
            System.out.println("用户不存在 插入用户数据");
            //保存用户登录数据
            User user1=new User();
            user1.setOpenId(openid);
            user1.setSessionKey(sessionKey);
            user1.setRegTime(new Date());
            user1.setVisitTime(new Date());
            user1.setUserType("小程序");

            iuserService.insert(user1);
            //新增用户信息数据
            User baseuser =iuserService.selectByOpenid(openid);

            Userinfo userinfo = new Userinfo();
            userinfo.setAvatarUrl(avatarUrl);
            userinfo.setNickName(nickName);
            userinfo.setGender(gender+"");
            userinfo.setUserId(baseuser.getId());

            iuserinfoService.insert(userinfo);

        } else {
            //已存在
            System.out.println("用户openid已存在");
            //user.setVisitTime(new Date());
            //iuserService.updateById(user);
        }

        //返回参数
        Map<String, Object> map = new HashMap<>();

        User tokenUser=new User();
        tokenUser.setOpenId(openid);
        tokenUser.setSessionKey(sessionKey);

        // JWT 返回自定义登陆态 Token
        String token = jwtConfig.createTokenByWxAccount(tokenUser);
        map.put("token",token);
        map.put("code", 200);
        return map;



    }








    /**
     * 获取openid
     *
     * @param code
     * @return
     */

    public static JSONObject getOpenId(String code) {


        JSONObject jsonObject = null;
        try {
            //配置参数
            Map<String, Object> parms = new HashMap<String, Object>();
            parms.put("appid", ApiConstant.APIID);
            parms.put("secret", ApiConstant.SECRET);
            parms.put("js_code", code);
            parms.put("grant_type", ApiConstant.GRANTTYPE);

            //发送请求
            Http http = new Http();
            String rs = http.sendGet(ApiConstant.WX_OPENIDURL, parms, "utf-8");

            jsonObject = JSON.parseObject(rs);

            String sessionKey = jsonObject.get("session_key").toString();
            String openId = jsonObject.get("openid").toString();
            System.out.println("openid=" + openId);

            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();

        }
        return jsonObject;
    }



}

